import collections
import re


def read_time_machine():
    with open(r".\MNIST\article.txt", "r") as f:
        lines = f.readlines()
    return [re.sub("[^A-Za-z]+", " ", line).lower() for line in lines]


lines = read_time_machine()
print(f"# text lines: {len(lines)}")
print(lines[0])
print(lines[10])


# 词元化
def tokenize(lines, token="word"):
    if token == "word":
        return [line.split() for line in lines]
    elif token == "char":
        return [list(line) for line in lines]
    else:
        print(f"error token:{token}")


tokens = tokenize(lines, token="char")
for i in range(11):
    print(tokens[i])


def count_corpus(tokens):
    result = []
    if len(tokens) == 0 or isinstance(tokens[0], list):
        for token in tokens:
            for temp in token:
                result.append(temp)
    return collections.Counter(result)


#print(count_corpus(tokens))
#print(len(count_corpus(tokens)))

class Vocab:
    def __init__(self, tokens=None, min_freq=0, reserved_token=None):
        if tokens is None:
            tokens = []
        if reserved_token is None:
            reserved_token = []

        # 按照出现频率进行排序
        counter = count_corpus(tokens)
        self.token_freqs = sorted(counter.items(), key=lambda x: x[1], reverse=True)
        # 未知词元索引为0
        self.unk = 0
        self.uniq_tokens = ["<unk>"] + reserved_token
        self.uniq_tokens += [token for token, freq in self.token_freqs if freq > min_freq and token not in reserved_token]
        self.idx_to_token, self.token_to_idx = [], dict()
        for token in self.uniq_tokens:
            self.idx_to_token.append(token)
            self.token_to_idx[token] = len(self.idx_to_token) - 1

    def __len__(self):
        return len(self.uniq_tokens)

    def __getitem__(self, tokens):
        if not isinstance(tokens, (list, tuple)):
            return self.token_to_idx.get(tokens, self.unk)
        return [self.__getitem__(token) for token in tokens]

    def to_tokens(self, indices):
        if not isinstance(indices, (list, tuple)):
            return self.idx_to_token[indices]
        return [self.to_tokens(index) for index in indices]


vocab = Vocab(tokens)
print(len(vocab))
print(vocab.idx_to_token)

for i in [0, 10]:
    print("words:", tokens[i])
    print("indices:", vocab[tokens[i]])


# 整合所有的功能
def load_corpus_time_machine(max_tokens=-1):
    lines = read_time_machine()
    tokens = tokenize(lines, "char")
    vocab = Vocab(tokens)
    corpus = [vocab[token] for line in tokens for token in line]
    if max_tokens > 0:
        corpus = corpus[:max_tokens]
    return corpus, vocab


corpus, vocab = load_corpus_time_machine()
print(len(corpus))